package com.ljt.service.impl;

import com.ljt.entity.BlogEntity;
import com.ljt.repository.BlogDao;
import com.ljt.service.BlogService;
import com.ljt.utils.HtmlFilter;
import org.hibernate.service.spi.ServiceException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * Created by wb-ljt251780 on 2017/7/19.
 */
@Service
@Transactional
public class BlogServiceImpl implements BlogService {
    @Resource
    private BlogDao blogDao;

    @Override
    public Page<BlogEntity> findAll(Pageable pageable) {
        return blogDao.findAll(pageable);
    }

    @Override
    public BlogEntity findById(Long id) {
        return blogDao.findOne(id);
    }

    @Override
    public void saveOrUpdate(BlogEntity blogEntity) {
        if (blogEntity == null) {
            throw new ServiceException("操作对象不能为空");
        }
        if (blogEntity.getId() != null) {
            BlogEntity dbBlog = findById(blogEntity.getId());
            dbBlog.setStatus(blogEntity.getStatus());
            dbBlog.setTitle(blogEntity.getTitle());
            dbBlog.setCategoryEntity(blogEntity.getCategoryEntity());
            dbBlog.setPrivacy(blogEntity.getPrivacy());
            dbBlog.setContent(blogEntity.getContent());
            dbBlog.setSummary(HtmlFilter.truncate(blogEntity.getContent(), 300));
            dbBlog.setTags(blogEntity.getTags());
            blogDao.saveAndFlush(dbBlog);
        }else{
            blogEntity.setCreateAt(new Date());
            blogEntity.setFeatured(0);
            blogEntity.setStatus(0);
            blogEntity.setViews(0);
            blogEntity.setSummary(HtmlFilter.truncate(blogEntity.getContent(), 300));
            blogDao.save(blogEntity);
        }
    }

}
